package com.hema.auction.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;

import com.iapppay.alpha.sdk.main.IAppPay;
import com.hema.auction.R;
import com.hema.auction.base.BaseRechargeActivity;
import com.hema.auction.event.TabIndexEvent;
import com.hema.auction.http.HttpTag;
import com.hema.auction.http.UrlManager;
import com.hema.auction.http.biz.HttpManager;
import com.hema.auction.utils.Constant;
import com.hema.auction.utils.Utils;
import com.hema.auction.widget.MyClickable;
import com.hema.auction.widget.view.TitleView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 充值
 * author by john
 */

public class RechargeActivity extends BaseRechargeActivity {
    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(R.id.tv_ten)
    TextView tvTen;
    @BindView(R.id.tv_one_hundred)
    TextView tvOneHundred;
    @BindView(R.id.tv_two_hundred)
    TextView tvTwoHundred;
    @BindView(R.id.tv_three_hundred)
    TextView tvThreeHundred;
    @BindView(R.id.tv_four_hundred)
    TextView tvFourHundred;
    @BindView(R.id.edit_amount)
    EditText etAmount;
    @BindView(R.id.tv_exchange_coin)
    TextView tvExchangeCoin;
    @BindView(R.id.tv_exchange_coin_unit)
    TextView tvExchangeCoinUnit;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.tv_payment_amount)
    TextView tvPaymentAmount;
    @BindView(R.id.rb_alipay)
    RadioButton rbAlipay;
    @BindView(R.id.rb_wechat)
    RadioButton rbWechat;
    @BindView(R.id.tv_recharge)
    TextView tvRecharge;
    @BindView(R.id.cb_agreement)
    CheckBox cbAgreement;
    @BindView(R.id.tv_agreement)
    TextView tvAgreement;

    private int amount;
    private String transid;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge);
        ButterKnife.bind(this);
        init();
        IAppPay.init(this, IAppPay.PORTRAIT, Constant.appid);
    }

    private void init() {
        tvTen.setSelected(true);
        amount = 10;
        index();
        etAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (etAmount.getText().toString().trim().length() > 0) {
                    amount = Integer.valueOf(etAmount.getText().toString().trim());
                    tvExchangeCoin.setText(String.valueOf(amount));
                    tvPaymentAmount.setText(String.valueOf(amount));
                    index();
                }
            }
        });
        etAmount.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    showToastSafe("huiche");
                }
                return false;
            }
        });

        rbAlipay.setOnClickListener(view -> {
            rbAlipay.setChecked(true);
            rbWechat.setChecked(false);
            payType = "alipay_h5";
            payMethod = 401;
        });
        rbWechat.setOnClickListener(view -> {
            payType = "wechat_h5";
            rbWechat.setChecked(true);
            rbAlipay.setChecked(false);
            payMethod = 403;
        });
        tvAgreement.setText(getClickableSpan());
        tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());
    }

    private CharSequence getClickableSpan() {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString(Constant.EXTRA_TITLE, getString(R.string.reg_agreement));
                bundle.putString(Constant.EXTRA_URL, UrlManager.H5_AGREEMENT);
                intentTo(H5Activity.class, bundle);
            }
        };
        SpannableString spanableInfo = new SpannableString(tvAgreement.getText().toString());
        int start = 4;
        int end = 10;
        spanableInfo.setSpan(new MyClickable(this, listener), start, end, Spanned.SPAN_MARK_MARK);
        return spanableInfo;
    }


    @OnClick({R.id.tv_ten, R.id.tv_one_hundred, R.id.tv_two_hundred
            , R.id.tv_three_hundred, R.id.tv_four_hundred
            , R.id.tv_recharge, R.id.edit_amount})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_ten:
                tvTen.setSelected(true);
                tvOneHundred.setSelected(false);
                tvTwoHundred.setSelected(false);
                tvThreeHundred.setSelected(false);
                tvFourHundred.setSelected(false);
                amount = 10;
                tvExchangeCoin.setText(String.valueOf(amount));
                tvPaymentAmount.setText(String.valueOf(amount));
                Utils.hideKeyboard(this);
                index();
                break;
            case R.id.tv_one_hundred:
                tvTen.setSelected(false);
                tvOneHundred.setSelected(true);
                tvTwoHundred.setSelected(false);
                tvThreeHundred.setSelected(false);
                tvFourHundred.setSelected(false);
                amount = 100;
                tvExchangeCoin.setText(String.valueOf(amount));
                tvPaymentAmount.setText(String.valueOf(amount));
                Utils.hideKeyboard(this);
                index();
                break;
            case R.id.tv_two_hundred:
                tvTen.setSelected(false);
                tvOneHundred.setSelected(false);
                tvTwoHundred.setSelected(true);
                tvThreeHundred.setSelected(false);
                tvFourHundred.setSelected(false);
                amount = 200;
                tvExchangeCoin.setText(String.valueOf(amount));
                tvPaymentAmount.setText(String.valueOf(amount));
                Utils.hideKeyboard(this);
                index();
                break;
            case R.id.tv_three_hundred:
                tvTen.setSelected(false);
                tvOneHundred.setSelected(false);
                tvTwoHundred.setSelected(false);
                tvThreeHundred.setSelected(true);
                tvFourHundred.setSelected(false);
                amount = 300;
                tvExchangeCoin.setText(String.valueOf(amount));
                tvPaymentAmount.setText(String.valueOf(amount));
                Utils.hideKeyboard(this);
                index();
                break;
            case R.id.tv_four_hundred:
                tvTen.setSelected(false);
                tvOneHundred.setSelected(false);
                tvTwoHundred.setSelected(false);
                tvThreeHundred.setSelected(false);
                tvFourHundred.setSelected(true);
                amount = 400;
                tvExchangeCoin.setText(String.valueOf(amount));
                tvPaymentAmount.setText(String.valueOf(amount));
                Utils.hideKeyboard(this);
                index();
                break;
            case R.id.edit_amount:
                tvTen.setSelected(false);
                tvOneHundred.setSelected(false);
                tvTwoHundred.setSelected(false);
                tvThreeHundred.setSelected(false);
                tvFourHundred.setSelected(false);
                if (etAmount.getText().toString().trim().length() > 0) {
                    amount = Integer.valueOf(etAmount.getText().toString().trim());
                } else {
                    amount = 0;
                }
                tvExchangeCoin.setText(String.valueOf(amount));
                tvPaymentAmount.setText(String.valueOf(amount));
                break;
            case R.id.tv_recharge:
                if (isLogin) {
                    if (amount > 0) {
//                        showProgressDialog();
                        if (cbAgreement.isChecked()) {
                            HttpManager.getInstance(this).recharge(String.valueOf(amount), payType, this);
                        } else {
                            showToastSafe(R.string.please_agree_privacy_agreement);
                        }

                    }
                } else {
                    goLogin();
                }
                break;

        }
    }


    private Call call;

    private void index() {
//        progressBar.setVisibility(View.VISIBLE);
//        tvExchangeCoin.setVisibility(View.GONE);
//        tvExchangeCoinUnit.setVisibility(View.GONE);
        if (call != null)
            if (call.isCanceled())
                call.cancel();
        call = HttpManager.getInstance(this).index(String.valueOf(amount), this);
    }

    @Override
    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {
        super.onSuccess(httpTag, call, result);
        switch (httpTag) {
            case TAG_DO_ORDER:
                try {
                    if (result.getInt("errcode") == 0) {
                        JSONObject data = result.getJSONObject("data");
                        transid = data.getString("transid");
                        startPay(1, transid, amount);
//                        orderSn = data.getString("orderSn");
//                        String payUrl = data.getString("payUrl");\
//                        toPay(1, payUrl);
                    } else {
                        showToastSafe(result);
                        dismissProgressDialog();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissProgressDialog();
                }
                break;
            case TAG_INDEX:
                try {
                    if (result.getInt("errcode") == 0) {
                        tvExchangeCoin.setText(result.getString("data"));
                        progressBar.setVisibility(View.GONE);
                        tvExchangeCoin.setVisibility(View.VISIBLE);
                        tvExchangeCoinUnit.setVisibility(View.VISIBLE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissProgressDialog();
                }
                break;
        }
    }

    @Override
    protected void paySuccess() {
        super.paySuccess();
        EventBus.getDefault().post(new TabIndexEvent(3));
        screenManager.popAllActivitys(MainActivity.class);
    }
}
